package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.example.demo.service
 * @Author: HUI
 * @CreateTime: 2022-03-11 20:58
 * @Description:
 */
@Service("userDetailsService")
public class MyUserService implements UserDetailsService {

    //推荐使用 构造方式写入，以防后面被修改
    private final UserMapper userMapper;

    @Autowired
    public MyUserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据库
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        //设置权限
        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new org.springframework.security.core.userdetails.User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()), list);
    }
}
